<template>
  <div class="login-page">
    <Swiper />
    <div class="content">
      <h3>直&nbsp;&nbsp;&nbsp;觉&nbsp;&nbsp;&nbsp;岛</h3>
      <div class="course-button">教&nbsp;&nbsp;程</div>
      <div class="login-button" @click="loginDialogBtn">登&nbsp;&nbsp;陆</div>
    </div>
  </div>
  <el-dialog v-model="loginDialogVisible" title="用户登陆" width="30%" center align-center>
    <el-form :model="loginForm" :rules="loginRules">
      <el-form-item label="用户名" :label-width="'60px'">
        <el-input v-model="loginForm.username" />
      </el-form-item>
      <el-form-item label="密码" :label-width="'60px'">
        <el-input v-model="loginForm.password" type="password" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="loginEvent"> 登陆 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import Swiper from "@/components/Swiper.vue";
import { LoginApi } from "@/api";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const router = useRouter();
const loginDialogVisible = ref(false);
const loginForm = reactive({
  username: "",
  password: "",
});

const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {min:3,max:11,message:'用户名长度在3到11个字符之间',trigger:'blur'}
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {min:3,max:16,message:'密码长度在3到16个字符之间',trigger:'blur'}
  ]
})


const loginDialogBtn = () => {
  const user = localStorage.getItem("user");
  if (user) {
    router.replace("/main");
  } else {
    loginDialogVisible.value = true;
  }
};

const loginEvent = async () => {
  const res = await LoginApi(loginForm);
  console.log(res);
  if (res.data.code == 0) {
    localStorage.setItem("token", res.data.data.token);
    localStorage.setItem("user", JSON.stringify(res.data.user));
    ElMessage({
      message: "登陆成功",
      type: "success",
    });
    loginDialogVisible.value = false;
    router.push("/main");
  } else {
    ElMessage({
      message: "用户名或密码错误",
      type: "error",
    });
  }
};

</script>
<style scoped>
.login-page {
  width: 100%;
  height: 100%;
}

.content {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 20;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
}

.content h3 {
  width: 250px;
  text-align: center;
  font-size: 50px;
  font-weight: 600;
  color: #fff;
  margin-bottom: 100px;
  -webkit-text-stroke: 1px skyblue;
  text-shadow: 5px 5px 10px rgba(0, 0, 0, 0.6);
}

.content .course-button,
.content .login-button {
  width: 150px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  background-color: #d64848;
  border-radius: 20px;
  margin: 10px;
}
</style>
